package com.harmony.pilot.completion.client;

import com.harmony.pilot.common.dto.BuildInfo;
import com.harmony.pilot.common.dto.CodeContext;
import com.harmony.pilot.common.dto.CompletionItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Collections;
import java.util.List;

/**
 * 构建服务客户端
 */
@Slf4j
@Component
public class BuildServiceClient {
    
    private final WebClient webClient;
    
    public BuildServiceClient(@Value("${service.build.url}") String buildServiceUrl) {
        this.webClient = WebClient.builder()
                .baseUrl(buildServiceUrl)
                .build();
    }
    
    /**
     * 获取构建信息
     */
    public BuildInfo getBuildInfo(String projectRoot) {
        try {
            return webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/build/info")
                            .queryParam("projectRoot", projectRoot)
                            .build())
                    .retrieve()
                    .bodyToMono(BuildInfo.class)
                    .block();
        } catch (Exception e) {
            log.error("Failed to get build info", e);
            return null;
        }
    }
    
    /**
     * 获取GN补全
     */
    public List<CompletionItem> getGnCompletions(CodeContext context) {
        try {
            return webClient.post()
                    .uri("/build/gn/completions")
                    .bodyValue(context)
                    .retrieve()
                    .bodyToFlux(CompletionItem.class)
                    .collectList()
                    .block();
        } catch (Exception e) {
            log.error("Failed to get GN completions", e);
            return Collections.emptyList();
        }
    }
}

